extends CharacterBody2D


@export var SPEED = 80
const JUMP_VELOCITY = -400.0
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D

var is_game_over :bool = false #是否死亡

@export var bullet_scene : PackedScene #创建子弹 设置子弹场景
var fire_cd_rd :bool = true # 发射cd就绪

@onready var fire_timer :Timer = $Timer

func _physics_process(delta: float) -> void:
	#下坠
	#if not is_on_floor():
		#velocity += get_gravity() * delta
	#跳跃
	#if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		#velocity.y = JUMP_VELOCITY
	#左右移动
	#var direction := Input.get_axis("ui_left", "ui_right")
	#if direction:
		#velocity.x = direction * SPEED
	#else:
		#velocity.x = move_toward(velocity.x, 0, SPEED)
	# 播放动画
	#if velocity == Vector2.ZERO:
		#animated_sprite.play("idle")
	#else:
		#animated_sprite.play("run")
	#移动
	if not is_game_over:
		velocity = Input.get_vector("move_left","move_right","move_up","move_down") * SPEED
		move_and_slide()
		# 播放动画
		if Input.get_vector("move_left","move_right","move_up","move_down") == Vector2(0,0):
			animated_sprite.play("idle")
		else:
			animated_sprite.play("run")
	
	# 发射子弹
	if Input.get_vector("move_left","move_right","move_up","move_down") == Vector2(0,0) and not is_game_over:
		if fire_cd_rd == true:
			fire_bullet()
			fire_cd_rd = false
			fire_timer.start()

func _process(delta: float) -> void:
	# 播放音效
	if Input.get_vector("move_left","move_right","move_up","move_down") == Vector2(0,0) and not is_game_over:
		$RunSound.stop()
	elif not $RunSound.playing:
		$RunSound.play()


# 游戏结束
func game_over():
	if not is_game_over:
		is_game_over = true
		animated_sprite.play("dide")
		# 触发GM中结束
		get_tree().current_scene.show_game_over()
		# 播放声音
		$GameOverSound.play()

# 发射子弹CD
func _on_fire() -> void:
	#if Input.get_vector("move_left","move_right","move_up","move_down") != Vector2(0,0) or is_game_over:
		#return
	fire_cd_rd = true


# 发射子弹
func fire_bullet():
	# 射击声音
	$FireSound.play()
	# 生成子弹
	var bullet_node = bullet_scene.instantiate()
	bullet_node.position = position + Vector2(16,2)
	get_tree().current_scene.add_child(bullet_node)
